package com.zkyc.framework.common.utils;

import com.zkyc.framework.common.constant.Constant;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 通用工具类
 */
public class GeneralUtil {

    public static String getUUid(Integer num){
        String ud = UUID.randomUUID().toString().replaceAll("-", "");
        if (num!=null) {
            ud = ud.substring(0, num);
        }
        return ud;
    }
    // 随机字符串生成 // length表示生成字符串的长度
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@#￥%&$*()";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    // 手机号中间4位*
    public static String phoneNumHandler(String phone) {
        if (StringUtils.isBlank(phone)) {
            return phone;
        }
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
    }

    // 自定义列表分页
    public static List<?> listCusFrom(List<?> list, int from, int num) {
        int total;
        if (list !=null && list.size() !=0) {
            total = list.size();
            int end = from *num;
            int start = (from-1) *num;
            if (from > total/num) {
                end = total;
            }

            if (start >end) {
                // 最后一页
                start = (total/num) *num;
            }
            list = list.subList(start, end);
        }
        return list;
    }

    /**
     * 去重
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    /**
     * 页码转索引下标
     * @param from 1
     * @return
     */
    public static int indexFrom(int from) {
        from = from ==0 ? 1 : from;
        return (from -1) * Constant.PageSize10;
    }

    public static int index20From(int from) {
        from = from ==0 ? 1 : from;
        return (from -1) *Constant.PageSize20;
    }
    // 自定义
    public static int indexCustomFrom(int from, int size) {
        from = from ==0 ? 1 : from;
        return (from -1) * size;
    }

}
